'''
This file is part of DopplerShift.

    DopplerShift is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    DopplerShift is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with DopplerShift.  If not, see <http://www.gnu.org/licenses/>.
'''

from lxml import etree
import datetime

class DSXMLSerializer(object):
    def __init__(self, root_name, dict_doc):
        self._root = etree.Element(root_name)
        self._dict_doc = dict_doc
    def __call__(self, get_as_etree=False):
        self._processDictObject(self._root, self._dict_doc)
        if get_as_etree == False:
            return etree.tostring(self._root)
        return self._root
    def _processDictObject(self, parent, obj):
        for k,v in obj.iteritems():
            if isinstance(v, dict):
                e = etree.SubElement(parent, k)
                self._processDictObject(e, v)
            elif isinstance(v, list):
                self._processListObject(parent, k, v)
            elif isinstance(v, str) or isinstance(v, unicode): 
                self._processStringObject(parent, k, v)
            elif isinstance(v, datetime.datetime):
                self._processDatetimeObject(parent, k, v)
            else:
                self._processStringObject(parent, k, str(v))
    def _processDatetimeObject(self, parent, key, value):
        parent.set(key, value.strftime("%Y-%M-%d  %H:%M"))
    def _processStringObject(self, parent, key, value):
        parent.set(key, value)
    def _processListObject(self, parent, key, obj):
        for el in obj:
            e = etree.SubElement(parent, key)
            if isinstance(el, dict):
                self._processDictObject(e, el)
            elif isinstance(el, list):
                self._processListObject(e, 'item', el)
            elif isinstance(el, unicode) or isinstance(el, str):
                e.text = el
            else:
                e.text = str(el) 
